<!--
 * @description  : 市管-日计划制定-添加临时任务列表-辽宁
 * @descriptionDetail: 市管-日计划制定-添加临时任务列表-辽宁
 * @copyright    : 浙江烟草
 * @author       : bln
 * @create       : 2022-09-02 14:57:44
-->
<template>
	<view class="page">
		<!-- #ifdef H5-ONLY -->
		<theme-navbar :is-white="false" :title="navTitle" :custom-back="goBack" style="z-index: 99999">
			<view class="nav-right-icon">
				<view @tap="handlerSure">
					确定
				</view>
			</view>
		</theme-navbar>
		<!-- #endif -->
		<!-- #ifdef H5-WECHAT || H5-EMP -->
		<fab-button :content="fContent" @fabtrigger="fabtrigger" />
		<!-- #endif -->
		<view>
			<u-search class="search-space" shape="round" :clearabled="true" :showAction="true" actionText="确定" :animation="true" placeholder="请输入企业字号、许可证号、地址" v-model="searchData.keyWord" @custom="handlerSearch"></u-search>
			<u-dropdown class="" ref="searchDropDown" @open="handlerOpen" @close="handlerClose">
				<u-dropdown-item :title="curOrgName" :options="[]" v-model="searchData.orgUuid" @change="handlerChangeItem"></u-dropdown-item>
				<u-dropdown-item title="任务主体">
					<view class="slot-ts">
						<u-cell-group :border="false">
							<u-cell-item :title="ix.bcbName" :arrow="false" v-for="ix in licOptions" :key="ix.bcbId" @click="selectTaskSubject(ix)">
								<u-icon v-if="ix.checked" slot="right-icon" size="40" :color="$theme.u_type_primary" name="checkbox-mark"></u-icon>
							</u-cell-item>
						</u-cell-group>
					</view>
				</u-dropdown-item>
				<u-dropdown-item title="年检查次数">
					<view class="slot-content">
						<view class="item-box">
							<u-input type="number" placeholder="请输入" :border="true" v-model="searchData.checkCountStart"></u-input>
							<text class="txt-sty">
								-
							</text>
							<u-input type="number" placeholder="请输入" :border="true" v-model="searchData.checkCountEnd"></u-input>
						</view>
						<u-button type="primary" @click="handlerCount">
							确定
						</u-button>
					</view>
				</u-dropdown-item>
			</u-dropdown>
			<u-gap class="u-gap-sty" :height="$theme.cm_gap_height" :bg-color="$theme.cm_gap_color"></u-gap>
		</view>
		<view class="content u-page u-p-t-30">
			<mescroll-list :i="0" :index="0" :height="getListViewHeight()" :load-data="loadData" :initLoad="false" ref="mescrollItem0">
				<view slot-scope="d">
					<u-row style="border-bottom: 1px solid #e5e5e5; padding: 5px 0px;" @tap="handlerSelectItem(d.data)">
						<u-col span="10">
							<client-item :client="d.data"></client-item>
						</u-col>
						<u-col span="2" style="text-align:right;">
							<u-icon name="checkbox-mark" :color="$theme.u_type_primary" size="38" style="margin-right: 10px;" v-if="selectedUids.includes(d.data.retailerUuid)"></u-icon>
						</u-col>
					</u-row>
				</view>
			</mescroll-list>
		</view>
		<!-- </view> -->
		<!-- 组织机构选择 -->
		<u-popup mode="bottom" height="80%" v-model="orgSelectShow" @close="handlerCloseOrg">
			<org-select :parentUuid="parentUuid" :cleanParentOrg="true" :isHybrid="true" limitNodeType="all" treeType="zm-all-noright" @choose="handlerChooseOrg"></org-select>
		</u-popup>
		<u-select v-model="isShow" title="选择任务来源" mode="mutil-column-auto" :list="taskSourceList" @confirm="sourceConfirm"></u-select>
		<view class="space-content"></view>
		<view class="submit-btns btn-other-cls" v-if="searchData.taskSource && searchData.taskSourceItem">
			<u-button class="u-btn" style="width: 99%;" type="primary" size="medium" @click="addNoLicense">
				无证户采集
			</u-button>
		</view>
		<u-popup :mask-close-able="false" v-model="AcceptanceShow" border-radius="20" mode="center" width="80%" height="306rpx">
			<view class="good-popup-lay">
				<view style="margin: 32rpx 0;">
					<u-form-item label-width="150" label="受理单号:" label-position="left">
						<u-input v-model="applyCode" placeholder="请输入" :needValid="true"></u-input>
					</u-form-item>
				</view>
				<view class="good-popup-lay__btns">
					<u-button plain type="primary" size="medium" @click="() => { AcceptanceShow = false; applyCode = ''; selectedUids = selectedItems = []}">
						取&nbsp;&nbsp;&nbsp;&nbsp;消
					</u-button>
					<u-button type="primary" size="medium" @click="saveAcceptance">
						保&nbsp;&nbsp;&nbsp;&nbsp;存
					</u-button>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import MescrollList from "@/components/mescroll_list.vue";
	import MescrollMoreMixin from "@/components/mescroll-uni/mixins/mescroll-more.js";
	import OrgSelect from "@/components/org-select.vue"
	import checkService from "@/service/check/check.service"
	import ClientItem from './components/client-item.vue';
	import { M_TASK_SOURCE, L_SUBJECT_TYPE } from "@/service/check/mapping/enum.js";
	import fabButton from '@/components/uni-fab.vue';

	export default {
		components: {
			MescrollList,
			ClientItem,
			OrgSelect,
			fabButton
		},
		mixins: [MescrollMoreMixin, ],
		data() {
			return {
				M_TASK_SOURCE,
				L_SUBJECT_TYPE,
				keyword: '',
				orgSelectShow: false,
				selectedUids: [], // 选中项的ids
				selectedItems: [], // 选中项
				searchData: { // 查询参数
					keyWord: '', // 模糊搜索关键字
					orgUuid: '',
					taskType: '',
					checkDate: '',
					taskSubject: "01",
					taskSubjectItem: '',
					taskSource: '',
				},
				taskSource: [],
				taskTypeOptions: [],
				taskStatus: [],
				retailerLicStatusOptions: [],
				licOptions: [],
				monthOptions: [],
				optTaskSource: '',
				planList: [],
				newList: [],
				isSingle: false, // 是否单选，默认多选
				isDisabled: false,
				isRelRetailer: false, // 是否是关联经营户
				newTitle: '',
				isDayPlan: false, // 是否是日计划
				taskSourceList: [],
				nextPersons: [],
				isShow: false,
				parentUuid: '',
				curOrgName: '组织机构',
				AcceptanceShow: false,
				applyCode: '',
				isReturn: false,
				fContent: [{
					iconPath: require('@/static/confirm.png'),
					selectedIconPath: require('@/static/confirm.png'),
					text: '确定',
					active: false,
				}],
			};
		},
		onLoad(opt) {
			// 是否单选
			// this.isSingle = opt.isSingle;
			this.applyCode = opt.applyCode;
			// L_SUBJECT_TYPE.RETAILER;
			this.searchData.taskSubject = L_SUBJECT_TYPE.RETAILER;
			// 是否是关联经营户
			this.isRelRetailer = opt.isRelRetailer;
			this.newTitle = opt.title ? opt.title : '临时任务';
			this.searchData.taskSource = opt.taskSource ? opt.taskSource : '';
			// 检查添加临时任务
			this.searchData.taskSourceItem = opt.taskSourceItem ? opt.taskSourceItem : '';
			this.searchData.orgUuid = this.curUser.user.depart.orgUuid; // this.curUser.docOrgUuid;
			this.parentUuid = this.curUser.user.depart.orgUuid;
			this.curOrgName = this.curUser.user.depart.orgName;
			// 日计划添加临时任务时，需要选择任务来源
			this.isDayPlan = opt.isDayPlan ? opt.isDayPlan : false;

			if (this.isDayPlan) {
				this.setSourceData();
			}
			this.planList = this.getRouteParam() ? this.getRouteParam() : [];
		},
		created() {
			let mtsArr = this.$store.state.dicts['M_TASK_SUBJECT'];
			let mtsiArr = this.$store.state.dicts['M_TASK_SUBJECT_ITEM'];
			mtsArr.forEach(ipt => {
				this.licOptions.push({
					bcbCode: ipt.bcbCode,
					bcbName: ipt.bcbName,
					bcbId: ipt.bcbId,
					checked: this.searchData.taskSubject == ipt.bcbCode && this.searchData.taskSubjectItem == '',
					ext: ipt,
				});
				let subArr = mtsiArr.filter(ix => {
					return ix.parentBcbCode == ipt.bcbCode;
				});
				subArr.forEach(iop => {
					this.licOptions.push({
						bcbCode: iop.bcbCode,
						bcbName: `\u00A0\u00A0\u00A0\u00A0${iop.bcbName}`,
						bcbId: iop.bcbId,
						checked: this.searchData.taskSubjectItem == iop.bcbCode,
						parentBcbCode: iop.parentBcbCode,
						parentBctPhName: iop.parentBctPhName,
						ext: iop,
					});
				});
			});
		},
		mounted() {
			this.updateTitle();
		},
		methods: {
			setRightBtns() {
				// 设置右侧标题
				// #ifdef H5-DINGDING
				// 先放开右侧标题
				this.$deviceApi.setRight('确定', () => {
					// 添加日计划操作
					this.handlerSure();
					this.setRightBtns();
				}, true, true);
				// #endif
			},
			fabtrigger(btn) {
				if (btn.index == 0) {
					this.handlerSure();
				}
			},
			// 设置任务来源
			setSourceData() {
				let list = this.$store.state.dicts['M_TASK_SOURCE'];
				let itemlist = this.$store.state.dicts['M_TASK_SOURCE_ITEM'];
				list.forEach((item) => {
					if (item.value == M_TASK_SOURCE.REPORT_COMPLAINT ||
						item.value == M_TASK_SOURCE.TURN_TO_HOLD_ASSIGN ||
						item.value == M_TASK_SOURCE.OTHER) {
						let source = {
							value: item.value,
							label: item.label,
							children: itemlist.filter((sub) => {
								return item.value == sub.parentBcbCode
							}),
						};
						this.taskSourceList.push(source);
					}
				});
			},
			getListViewHeight() {
				let p = (this.$u.sys().windowHeight - 44 - uni.upx2px(90) - this.$u.sys().statusBarHeight) + 'px';
				// #ifdef H5-DINGDING || H5-WECHAT
				p = (this.$u.sys().windowHeight - uni.upx2px(90) - this.$u.sys().statusBarHeight) + 'px';
				// #endif
				return p;
			},
			selectTaskSubject(ix) {
				for (let i = 0; i < this.licOptions.length; i++) {
					if (this.licOptions[i].bcbId == ix.bcbId) {
						this.licOptions[i].checked = !this.licOptions[i].checked;
						if (ix.parentBcbCode) {
							this.searchData.taskSubject = ix.parentBcbCode;
							this.searchData.taskSubjectItem = ix.bcbCode;
						} else {
							this.searchData.taskSubject = ix.bcbCode;
							this.searchData.taskSubjectItem = '';
						}
					} else {
						this.licOptions[i].checked = false;
					}
				}
				this.$refs.searchDropDown.close();
				this.handlerSearch();
			},
			updateTitle() {
				this.$deviceApi.setTitle && this.$deviceApi.setTitle(this.newTitle);
				this.navTitle = this.newTitle;
				this.$forceUpdate();
			},
			handlerSearch() {
				// this.$refs['mescrollItem0'].refresh();
				let mescroll = this.getMescroll(0);
				mescroll && mescroll.triggerDownScroll();
			},
			// 选中
			handlerSelectItem(item) {
				if (this.isSingle) {
					this.selectedUids = [item.retailerUuid, ];
					this.selectedItems = [item, ];
					return;
				}
				if (this.selectedUids.includes(item.retailerUuid)) {
					this.selectedItems = this.selectedItems.filter(it => it.retailerUuid != item.retailerUuid);
				} else {
					this.selectedItems.push(item);
				}
				this.selectedUids = [];
				this.selectedItems.forEach(it => this.selectedUids.push(it.retailerUuid));
			},
			handlerOpen(idx) {
				// 组织机构 0
				idx == 0 && (this.orgSelectShow = true);
				this.$refs.searchDropDown.highlight();
			},
			handlerClose(idx) {
				this.orgSelectShow = false;
				this.$refs.searchDropDown.highlight(idx);
			},
			handlerChooseOrg(orgs) {
				if (orgs.length == 0) {
					this.$u.toast('请选择组织机构');
					return;
				}
				this.searchData.orgUuid = orgs[0].id;
				// this.orgSelectShow = false;
				this.curOrgName = orgs[0].name;
				this.$refs.searchDropDown.close();
				this.handlerSearch();
			},
			handlerCloseOrg() {
				this.$refs.searchDropDown.close();
			},
			// 选择搜索条件项
			handlerChangeItem() {
				console.log(this.searchData);
				this.handlerSearch();
			},
			// 填写年检查次数
			handlerCount() {
				this.$refs.searchDropDown.close();
				this.handlerSearch();
			},
			// 列表查询数据
			loadData(page) {
				// 调用后台接口查询数据：分页参数page.size, page.num
				return this.searchData.taskSubject == L_SUBJECT_TYPE.UN_LICENSE ? checkService.findRetailerList({
					page: page.num,
					limit: page.size,
					...this.searchData,
				}) : checkService.findRetailerList({
					page: page.num,
					limit: page.size,
					...this.searchData,
				});
			},
			toSelectPerson(){
				this.$u.route({
					url: '/pages/commonPage/flowUserSelectComponent',
					params: {
						flowFormCode: 'checkTempApproval', // 临时任务审批的gfcode
					}
				});
			},
			updateBackState(param) {
				let nextPersons = []
				if (param.flowUserSelectBack) {
					// 选择审批人
					for (let fu of param.flowUserSelectBack) {
						nextPersons.push(fu.personId);
					}
				}
				if (nextPersons.length === 0) {
					this.$u.toast('请选择审批人');
				} else {
					this.handleTempTask(nextPersons)
				}
			},
			// 检查添加临时任务
			handleTempTask (persons) {
				let message = '';
				this.$u.loading('加载中');
				this.isReturn = true;
				const params = {
					applyCode: this.applyCode || '',
					taskSource: this.searchData.taskSource,
					taskSubject: this.searchData.taskSubject,
					taskSourceItem: this.searchData.taskSourceItem,
					retailerUuid: this.selectedItems.map(item => item.retailerUuid),
					nextPersonUuids: persons.join(',')
				}
				checkService.submitTempClient(params).then(dr => {
					this.$u.hideLoading();
					if (dr.success) {
						// if (dr.msg) {
						// 	message = dr.msg;
						// } else {
						// 	message = '添加成功！';
						// }
						this.$u.toast("已填加到临时任务清单中，需审核请勿重复添加");
						// 辽宁添加零售任务需要领导审核 才能到日计划列表 故此这里不能返回数据 fsx 2023-12-8 开始
						setTimeout(()=>{
							this.backPrev({
								paramKey: 'temporaryTask',
								param: [],
							});
						},1500)
						// 辽宁添加零售任务需要领导审核 才能到日计划列表 故此这里不能返回数据 fsx 2023-12-8 结束
					} else {
						this.$u.toast(dr.msg);
					}
				}).catch((err)=>{
					this.$u.hideLoading();
					this.$u.toast(JSON.stringify(err));
				});
			},
			// 确定
			handlerSure() {
				let self = this;
				if (!this.isDayPlan && !this.$u.test.isEmpty(this.selectedItems)) {
					// 选择关联经营户
					if (this.isRelRetailer) {
						this.backPrev({
							paramKey: 'temporaryTask',
							param: this.selectedItems,
						});
						this.selectedUids = this.selectedItems = [];
					} else {
						if (!this.isReturn) {
							if (this.isSingle) {
								this.handleTempTask()
							} else {
								this.toSelectPerson()
							}
						}
					}
				} else {
					// 计划添加临时任务
					if (this.selectedItems.length == 0) {
						this.$u.toast('请选择任务');
						return;
					}
					if (this.planList.length > 0) {
						this.planList.forEach(item => {
							self.newList.push(item.retailerUuid);
						});
					}
					let idList = self.selectedItems.filter(r => {
						return self.newList.includes(r.retailerUuid)
					})
					if (idList.length > 0) {
						this.$u.hideLoading();
						this.selectedItems.filter(item => {
							if (item.retailerUuid == idList[0].retailerUuid) {
								this.$u.toast(`【${item.companyName}】已存在`);
							}
						})
						return
					}
					// 日计划 需要选择任务来源
					if (this.isDayPlan) {
						this.isShow = true;
					} else {
						this.backPrev({
							paramKey: 'temporaryTask',
							param: this.selectedItems,
						});
						this.selectedUids = this.selectedItems = [];
					}
				}
			},
			addNoLicense() {
				// 采集无证户
				if (this.$u.test.isEmpty(this.applyCode)) {
					this.$u.route('/pages/query/nolicence/add/addNolicence?isAddTempTask=false&taskSource=' + this.searchData.taskSource + '&taskSourceItem=' + this.searchData.taskSourceItem);
				} else {
					this.$u.route('/pages/query/nolicence/add/addNolicence?isAddTempTask=false&taskSource=' + this.searchData.taskSource + '&taskSourceItem=' + this.searchData.taskSourceItem + '&applyCode=' + this.applyCode);
				}
			},
			// 任务来源确认事件
			sourceConfirm(e) {
				console.log(e);
				this.isShow = false;
				this.selectedItems.forEach((item) => {
					item.taskSource = e[0].value;
					item.taskSourceItem = e[1].value;
				});
				if (e[1].value != '04') {
					this.backPrev({
						paramKey: 'temporaryTask',
						param: this.selectedItems,
					});
					this.selectedUids = this.selectedItems = [];
				} else {
					this.AcceptanceShow = true;
				}
			},
			saveAcceptance() {
				if (this.$u.test.isEmpty(this.applyCode)) return this.$u.toast('请输入受理单号')
				this.selectedItems.filter(item => {
					let obj = item;
					this.$set(obj, 'applyCode', this.applyCode)
				})
				this.backPrev({
					paramKey: 'temporaryTask',
					param: this.selectedItems,
				});
				this.selectedUids = this.selectedItems = [];
			},
		},
	};
</script>

<style lang="scss" scoped>
	.page {
		padding: 0;
	}

	.slot-content {
		background-color: #FFFFFF;
		padding: 32rpx 32rpx;

		.item-box {
			margin-bottom: 32rpx;
			display: flex;
			flex-wrap: wrap;
			justify-content: space-between;
		}
	}

	/deep/.u-dropdown__menu .u-dropdown__menu__item:first-child .u-flex {
		overflow: hidden;
		height: 100%;
	}

	.txt-sty {
		line-height: 60rpx;
		padding: 0 10px;
	}

	.search-space {
		padding: $cm-search-padding-row $cm-search-padding-column;
		padding-bottom: 6px;
	}

	.u-gap-sty {
		position: relative;
	}

	.good-popup-lay {
		padding: $cm-content-paddng-row;
		width: 100%;
		height: 100%;

		&__title {
			font-size: 36rpx;
			font-weight: 600;
			color: $u-main-color;
			margin: 10rpx 0;
			text-align: center;
			width: 100%;
		}

		&__btns {
			width: 100%;
			margin-top: 24rpx;
			display: flex;
			flex-direction: row;
			justify-content: space-between;

			uni-button {
				flex: 0.28;
			}
		}
	}
</style>
